package lesson02;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UDPEchoServer02 {
    private DatagramSocket socket;

    public UDPEchoServer02(int port) throws SocketException {
        if (port < 1024 || port > 65535) {
            throw new BindException("应该设置接口在1024 —— 65535之间");
        }
        this.socket = new DatagramSocket(port);  //自动设置了ip地址，只需要设置接口号就行
    }

    public void start() throws IOException {
        System.out.println("服务端启动.");
        while (true) {
            //1.设置接收数据的大小
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            //2、接收数据
            socket.receive(requestPacket);    //为什么接收到数据就直接在传参的变量中直接赋值了？？？
            //3、解析数据  为什么要使用String来解析数据?????
            String request = new String(requestPacket.getData(),
                    0, requestPacket.getLength(), "UTF-8");
            //4、处理数据
            String response = process(request);
            //5、整理数据发回响应     UPD不是一个不需要响应的网络协议吗？为什么这里还需要打包好数据发回客户端？？？
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),
                    0,response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] request = %s response = %s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(),request,response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServer02 udpEchoServer02 = new UDPEchoServer02(9999);
        udpEchoServer02.start();
    }


}
